<template>
    <div>
        <div>
            <el-form ref="searchForm" :inline="true" :model="condition.search" label-suffix="" label-width="100px"
                     label-position="left" size="small">
                <el-row>
                    <el-col>
                        <el-form-item label="企业" prop="workCorpId">
                            <el-select v-model="condition.search.workCorpId" placeholder="请选择企业"
                                       style="width:200px;">
                                <el-option
                                    v-for="item in corps"
                                    :key="item.id"
                                    :label="item.corpName"
                                    :value="item.id">
                                    {{ item.corpName }}
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="类型" prop="type">
                            <el-select v-model="condition.search.type"
                                       placeholder="类型">
                                <el-option label="文档"
                                           value="DOCUMENT"></el-option>
                                <el-option label="文本"
                                           value="TEXT"></el-option>
                                <el-option label="图片"
                                           value="IMAGE"></el-option>
                                <el-option label="H5链接"
                                           value="H5"></el-option>
                                <el-option label="视频"
                                           value="VIDEO"></el-option>
                                <el-option label="小程序"
                                           value="MNP"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="getData">查询</el-button>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="showAddDialog">新增</el-button>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="reset">重置</el-button>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </div>

        <el-table
            v-if="mode === 'list'"
            id="mainTable"
            size="small"
            :data="tableData"
            header-cell-class-name="tableHeaderStyle"
            :row-class-name="tableRowClassName">
            <el-table-column label="序号" width="60">
                <template v-slot="scope">
                    <span>{{ (condition.page - 1) * condition.rows + scope.$index + 1 }}</span>
                </template>
            </el-table-column>
            <el-table-column
                prop="workCorpName"
                label="企业名称">
            </el-table-column>
            <el-table-column
                prop="type"
                :formatter="formatType"
                label="类型">
            </el-table-column>
            <el-table-column
                prop="title"
                label="标题">
                <template v-slot="scope">
                    <a :href="scope.row.fileUrl" target="_blank" v-if="scope.row.type === 'DOCUMENT'">
                        {{ scope.row.title }}
                    </a>
                    <a :href="scope.row.h5Link" target="_blank" v-else-if="scope.row.type === 'H5'">
                        {{ scope.row.title }}
                    </a>
                    <span v-else>
                        {{ scope.row.title }}
                    </span>
                </template>
            </el-table-column>
            <el-table-column
                prop="fileSize"
                width="80px"
                label="大小">
                <template v-slot="scope">
                    <div v-if="scope.row.fileSize">
                        {{ scope.row.fileSize }}KB
                    </div>
                    <div v-else>
                        -
                    </div>
                </template>
            </el-table-column>
            <el-table-column
                width="150px"
                label="内容">
                <template v-slot="scope">
                    <material-show :info="scope.row" :preview-src-list="mediaUrls"></material-show>
                </template>
            </el-table-column>
            <el-table-column
                prop="mediaId"
                label="微信媒体ID">
            </el-table-column>
            <el-table-column
                prop="mediaExpiryTime"
                label="媒体过期时间">
            </el-table-column>
            <el-table-column
                prop="createTime"
                label="创建时间">
            </el-table-column>
            <el-table-column
                prop="updateTime"
                label="更新时间">
            </el-table-column>
            <el-table-column
                label="操作"
                fixed="right"
                align="center"
                width="120">
                <template v-slot="scope">
                    <div>
                        <el-button @click="onRefresh(scope.row)" type="text" size="small">刷新</el-button>
                        <el-button @click="showUpdateDialog(scope.row)" type="text" size="small">编辑</el-button>
                        <el-button @click="onDelete(scope.row)" type="text" size="small">删除</el-button>
                    </div>
                </template>
            </el-table-column>
        </el-table>
        <div v-if="mode === 'select'">
            <el-row
                v-for="item in rowsData" :key="item.id">
                <el-col :span="4" v-for="col in item.cols" :key="item.id">
                    <div>
                        <material-show :info="col" :preview-src-list="mediaUrls"></material-show>
                        <div class="album-text">
                            <div class="text-overflow">
                                标题：
                                <a :href="col.fileUrl" target="_blank" v-if="col.type === 'DOCUMENT'">
                                    {{ col.title }}
                                </a>
                                <a :href="col.h5Link" target="_blank" v-else-if="col.type === 'H5'">
                                    {{ col.title }}
                                </a>
                                <span v-else>{{ col.title }}</span>
                            </div>
                            <div>
                                大小：{{ col.fileSize }}KB
                            </div>
                            <div>
                                类型：{{ col.type }}
                            </div>
                            <div>
                                <el-button type="text" size="small" @click="onSelect(col)">
                                    选择
                                </el-button>
                            </div>
                        </div>
                    </div>
                </el-col>
            </el-row>
        </div>
        <el-pagination
            background
            small
            :hide-on-single-page="true"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page.sync="condition.page"
            :page-sizes="[10, 20, 30, 40, 50, 100]"
            :page-size.sync="condition.rows"
            layout="sizes, prev, pager, next"
            :total.sync="condition.total">
        </el-pagination>
        <el-dialog :title=addOrUpdateDialogTitle width="30%" :visible.sync="addOrUpdateDialogVisible">
            <el-form :model="addOrUpdateForm" label-width="120px" size="small">
                <el-form-item label="请选择企业">
                    <el-select v-model="addOrUpdateForm.workCorpId" placeholder="请选择企业" style="width:200px;" :disabled="disabled">
                        <el-option
                            v-for="item in corps"
                            :key="item.id"
                            :label="item.corpName"
                            :value="item.id">
                            {{ item.corpName }}
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="类型">
                    <el-select v-model="addOrUpdateForm.type" placeholder="类型" @change="selectChanged" :disabled="disabled">
                        <el-option label="文本"
                                   value="TEXT"></el-option>
                        <el-option label="文档"
                                   value="DOCUMENT"></el-option>
                        <el-option label="图片"
                                   value="IMAGE"></el-option>
                        <el-option label="H5链接"
                                   value="H5"></el-option>
                        <el-option label="视频"
                                   value="VIDEO"></el-option>
                        <el-option label="小程序"
                                   value="MNP"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="标题">
                    <el-input v-model="addOrUpdateForm.title" placeholder="标题"></el-input>
                </el-form-item>
                <el-form-item label="文本内容" v-if="addOrUpdateForm.type === 'TEXT'">
                    <el-input v-model="addOrUpdateForm.content" placeholder="文本内容" type="textarea"></el-input>
                </el-form-item>
                <el-form-item label="H5消息页面URL" v-if="addOrUpdateForm.type === 'H5'">
                    <el-input v-model="addOrUpdateForm.h5Link" placeholder="H5消息页面URL"></el-input>
                </el-form-item>
                <el-form-item label="H5消息摘要" v-if="addOrUpdateForm.type === 'H5'">
                    <el-input v-model="addOrUpdateForm.h5Desc" placeholder="H5消息摘要"></el-input>
                </el-form-item>
                <el-form-item label="小程序APP_ID" v-if="addOrUpdateForm.type === 'MNP'">
                    <el-input v-model="addOrUpdateForm.mnpAppId" placeholder="小程序APP_ID"></el-input>
                </el-form-item>
                <el-form-item label="小程序路径" v-if="addOrUpdateForm.type === 'MNP'">
                    <el-input v-model="addOrUpdateForm.mnpPage" placeholder="小程序消息打开后的路径"></el-input>
                </el-form-item>
                <el-form-item label="选择上传方式" v-if="addOrUpdateForm.type && addOrUpdateForm.type !== 'TEXT'">
                    <el-radio-group v-model="addOrUpdateForm.method">
                        <el-radio label="local">本地上传</el-radio>
                        <el-radio label="album">相册选择</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item :label=label
                              v-if="addOrUpdateForm.type && addOrUpdateForm.type !== 'TEXT' && addOrUpdateForm.method === 'local'">
                    <el-upload
                        ref="upload"
                        :action="upload()"
                        :multiple="false"
                        :limit="1"
                        :auto-upload="false"
                        :show-file-list="true"
                        :data="uploadData"
                        :file-list="fileList"
                        :on-change="handleChange"
                        :on-success="handleSuccess">
                        <el-button size="mini" type="success">点击上传</el-button>
                    </el-upload>
                    <div class="form-tips">
                        {{ uploadTips }}
                    </div>
                </el-form-item>
                <el-form-item :label=label
                              v-if="addOrUpdateForm.type && addOrUpdateForm.type !== 'TEXT' && addOrUpdateForm.method === 'album'">
                    <el-button @click="selectAlbumDialogVisible = true" size="mini" type="success">
                        点击选择
                    </el-button>
                    <div v-if="selectedAlbum.id" style="margin-top: 10px">
                        <media-show :url="selectedAlbum.url"></media-show>
                    </div>
                    <div class="form-tips">
                        {{ uploadTips }}
                    </div>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button size="small" @click="addOrUpdateDialogVisible = false">取 消</el-button>
                <el-button size="small" @click="addOrUpdateConfirm" type="primary"
                           v-loading.fullscreen.lock="uploadLoading">确 定
                </el-button>
            </div>
        </el-dialog>

        <el-dialog title="选择图片" width="70%" :visible.sync="selectAlbumDialogVisible" append-to-body>
            <album ref="albumSelect" size="small" @select="onSelectAlbum" mode="select"></album>
            <div slot="footer" class="dialog-footer"></div>
        </el-dialog>
    </div>
</template>

<script>
import {
    addWorkMaterial,
    deleteWorkMaterial,
    getUploadUrl,
    getWorkCorpByPage,
    getWorkMaterialByPage,
    refreshWorkMaterial,
    updateWorkMaterial
} from '@/api/api'
import TablePopover from "@/component/single/TablePopover";
import Album from "@/component/Album";
import MediaShow from "@/component/single/MediaShow";
import MaterialShow from "@/component/workwx/MaterialShow";
import {Message} from "element-ui";

export default {
    name: "WorkMaterial",
    components: {TablePopover, Album, MediaShow, MaterialShow},
    data() {
        return {
            // 分页搜索条件
            condition: {
                page: 1,
                rows: 10,
                total: 0,
                search: {}
            },
            // 表格数据
            tableData: [],
            // 新增或者编辑对话框显示
            addOrUpdateDialogVisible: false,
            // 标题
            addOrUpdateDialogTitle: '新增',
            // 新增或者编辑对话框表单
            addOrUpdateForm: {},
            // 选中行
            selectedRow: {},
            // 公司信息
            corps: [],
            // 文件列表
            fileList: [],
            // 上传附加数据
            uploadData: {
                category: 'material',
                type: '',
                localFlag: true
            },
            // 上传提示
            uploadTips: '',
            label: "上传资源",
            // 上传loading
            uploadLoading: false,

            // 图片或者视频url数组
            mediaUrls: [],

            selectAlbumDialogVisible: false,
            selectedAlbum: [],

            colsSize: 6,
            rowsSize: 0,
            rowsData: [],

            // 禁用
            disabled: false,
        }
    },
    // 这里定义需要父组件传过来的东西
    props: {
        size: {
            type: String,
            default: 'small'
        },
        mode: {
            type: String,
            default: 'list'
        },
        workCorpId: String
    },
    methods: {
        onSelect: function (row) {
            this.$emit('select', row)
        },
        selectChanged(value) {
            if (value === 'DOCUMENT') {
                this.uploadTips = '文档只能上传word/excel/ppt/pdf格式，最大支持20MB'
                this.uploadData.type = 'document';
                this.label = "上传文档";
            } else if (value === 'VIDEO') {
                this.uploadTips = "视频只能上传mp4格式，最大支持10MB"
                this.uploadData.type = 'video';
                this.label = "上传视频";
            } else {
                this.uploadTips = "图片只能上传jpg/jpeg/png格式，最大支持10MB"
                this.uploadData.type = 'image';
                if (value === 'IMAGE') {
                    this.label = "上传图片";
                } else if (value === 'H5') {
                    this.label = "H5消息封面图"
                } else if (value === 'MNP') {
                    this.label = "小程序封面图"
                }
            }
        },
        upload() {
            return getUploadUrl();
        },
        // 文件改变的时候钩子函数
        handleChange(file, fileList) {
            if (!this.addOrUpdateForm.title) {
                // this.$set(this.addOrUpdateForm, "title", file.name.substring(0, file.name.lastIndexOf(".")))
                this.$set(this.addOrUpdateForm, "title", file.name)
            }
        },
        // 文件上传成功后回调
        handleSuccess(response, file, fileList) {
            if (response.respCode != 1000) {
                Message.error('异常码：' + response.respCode + '，异常信息：' + response.respMsg);
                // 清空文件
                this.fileList = [];
                this.uploadLoading = false;
                return;
            }
            // 得到上传成功后服务器返回的数据
            this.addOrUpdateForm.fileUrl = response.body.url;
            this.addOrUpdateForm.fileSize = response.body.size;
            this.addOrUpdateForm.fileLocation = response.body.location;
            this.addOrUpdateForm.h5ImgUrl = this.addOrUpdateForm.fileUrl;
            this.addOrUpdateForm.mnpImgUrl = this.addOrUpdateForm.fileUrl;
            // 执行真正的上传操作
            this.addPure();
        },
        // 相册选择事件
        onSelectAlbum(row) {
            this.selectedAlbum = row;
            this.selectAlbumDialogVisible = false;
            this.addOrUpdateForm.fileUrl = row.url;
            this.addOrUpdateForm.fileSize = row.size;
            this.addOrUpdateForm.fileLocation = row.fileLocation;
            if (!this.addOrUpdateForm.title) {
                this.$set(this.addOrUpdateForm, "title", row.title)
            }
            this.addOrUpdateForm.h5ImgUrl = this.addOrUpdateForm.fileUrl;
            this.addOrUpdateForm.mnpImgUrl = this.addOrUpdateForm.fileUrl;
        },
        // 这里可以单独设置每一行的样式
        tableRowClassName({row, rowIndex}) {
            return '';
        },
        handleSizeChange(val) {
            this.getData();
        },
        handleCurrentChange(val) {
            this.getData();
        },
        // 格式布尔值
        formatBoolean: function (row, column, cellValue) {
            if (cellValue) {
                return "是";
            } else {
                return "否";
            }
        },
        formatType: function (row, column, cellValue) {
            if (cellValue === 'DOCUMENT') {
                return "文档";
            } else if (cellValue === 'TEXT') {
                return "文本";
            } else if (cellValue === 'IMAGE') {
                return "图片";
            } else if (cellValue === 'H5') {
                return "H5链接";
            } else if (cellValue === 'VIDEO') {
                return "视频";
            } else if (cellValue === 'MNP') {
                return "小程序";
            } else {
                return "未知";
            }
        },
        showAddDialog: function () {
            this.addOrUpdateDialogTitle = '新增';
            this.addOrUpdateDialogVisible = true;
            this.addOrUpdateForm = {};
            this.disabled = false;
        },
        showUpdateDialog: function (row) {
            this.addOrUpdateDialogTitle = '编辑';
            this.addOrUpdateDialogVisible = true;
            this.selectedRow = row;
            // 深拷贝
            this.addOrUpdateForm = Object.assign({}, row);
            this.disabled = true;
        },
        reset: function () {
            this.$refs['searchForm'].resetFields();
        },
        exportExcel: function () {
            this.GLOBAL.exportExcel('#mainTable', '数据.xlsx');
        },
        add: function () {
            if (this.addOrUpdateForm.type !== 'TEXT') {
                if (!this.addOrUpdateForm.method) {
                    this.$message({
                        type: 'error',
                        message: '请先上传文件'
                    });
                }
                if (this.addOrUpdateForm.method === 'local') {
                    let files = this.$refs.upload.uploadFiles
                    // 本地选择的判断条件
                    if (files.length === 0) {
                        this.$message({
                            type: 'error',
                            message: '请先选择文件!'
                        });
                    } else {
                        this.uploadLoading = true;
                        this.$refs.upload.submit();
                    }
                } else {
                    // 相册选择的判断条件
                    if (!this.selectedAlbum.id) {
                        this.$message({
                            type: 'error',
                            message: '请先选择文件!'
                        });
                    } else {
                        this.uploadLoading = true;
                        this.addPure();
                    }
                }
            } else {
                this.uploadLoading = true;
                this.addPure();
            }
        },
        addPure: function () {
            addWorkMaterial(this.addOrUpdateForm).then(data => {
                this.addOrUpdateDialogVisible = false;
                this.getData();
                this.fileList = [];
                this.uploadLoading = false;
            });
        },
        update: function () {
            updateWorkMaterial(this.addOrUpdateForm).then(data => {
                this.addOrUpdateDialogVisible = false;
                this.getData();
            });
        },
        onRefresh: function (row) {
            this.$confirm('请确认是否刷新，选择刷新之后会将过期文件重新上传到企业微信服务器，是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                refreshWorkMaterial({id: row.id}).then(data => {
                    this.$message({
                        type: 'success',
                        message: '刷新成功!'
                    });
                    this.getData();
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消'
                });
            });
        },
        onDelete: function (row) {
            this.$confirm('请确认是否删除, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                deleteWorkMaterial({id: row.id}).then(data => {
                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                    });
                    this.getData();
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消'
                });
            });
        },
        addOrUpdateConfirm: function () {
            if (this.addOrUpdateDialogTitle == '新增') {
                this.add();
            } else if (this.addOrUpdateDialogTitle == '编辑') {
                this.update();
            }
        },
        // 获取公司列表
        getCorps: function () {
            let condition = {
                page: 1,
                rows: 100,
                search: {}
            };
            getWorkCorpByPage(condition).then(data => {
                this.corps = data.body.rows;
            });
        },
        // 获取表格数据
        getData: function () {
            if (this.workCorpId) {
                this.condition.search.workCorpId = this.workCorpId;
            }
            getWorkMaterialByPage(this.condition).then(data => {
                this.tableData = data.body.rows;
                this.condition.total = data.body.total;
                this.tableData.forEach((item, index, arr) => {
                    if (item.type === 'IMAGE') {
                        this.mediaUrls.push(item.fileUrl);
                    } else if (item.type === 'H5') {
                        this.mediaUrls.push(item.h5ImgUrl)
                    } else if (item.type === 'MNP') {
                        this.mediaUrls.push(item.mnpImgUrl)
                    }
                })

                this.rowsData = [];
                this.rowsSize = Math.ceil(data.body.total / this.colsSize);
                for (let i = 0; i < this.rowsSize; i++) {
                    const temp = [];
                    for (let j = i * this.colsSize; j < this.tableData.length; j++) {
                        if (j < (i + 1) * this.colsSize) {
                            temp.push(this.tableData[j]);
                        } else {
                            break;
                        }
                    }
                    this.rowsData.push({
                        cols: temp
                    })
                }
            });
            this.getCorps();
        },
    },
    created() {
        this.getData();
    },
}
</script>

<style scoped>
.el-input {
    width: 150px !important;
}

.el-select {
    width: 150px !important;
}

.text-overflow {
    display: block;
    width: 31em;
    word-break: keep-all;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}
</style>
